package com.ltf.controller.adm;

import com.ltf.entity.Carousel;
import com.ltf.entity.XJson;
import com.ltf.service.CarouselService;
import com.ltf.service.LargeFileService;
import com.ltf.utils.PackJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

//轮播图管理
@RestController
@RequestMapping("/api/adm/carousel")
public class CarouselController {
    @Autowired
    CarouselService carouselService;
    @Autowired
    LargeFileService largeFileService;


    @GetMapping("/findById")
    public XJson findById(Integer id){
        Carousel byId = carouselService.findById(id);
        return PackJson.packX(200,"",byId);
    }

    @PostMapping("/update")
    public XJson update(Carousel carousel,
                        @RequestParam(value = "mypic",required = false)
                                MultipartFile myfile) throws IOException {
        if (myfile != null) {
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replace("-", "");
            if (carousel.getPic() != null && carousel.getPic().length() > 0) {
                this.largeFileService.delete(carousel.getPic());
            }
            carousel.setPic(uuid);
            this.largeFileService.add(uuid, myfile.getOriginalFilename(), myfile.getBytes());
        }
            int update = carouselService.update(carousel);
            List<Carousel> all = carouselService.findAll();
            return PackJson.packX(200, "修改成功", all);
        }


    @PostMapping("/add")
    public XJson add(Carousel carousel,
                     @RequestParam(value = "mypic",required = false)
                             MultipartFile myfile)throws IOException{
        //进行图片处理，不为空时
        if (myfile!=null){
            String uuid = UUID.randomUUID().toString();
            uuid = uuid.replace("-", "");
            if (carousel.getPic() != null && carousel.getPic().length() > 0) {
                this.largeFileService.delete(carousel.getPic());
            }
            //添加图片id
            carousel.setPic(uuid);
            this.largeFileService.add(uuid,myfile.getOriginalFilename(),myfile.getBytes());
            int add = carouselService.add(carousel);
        }
        List<Carousel> all = carouselService.findAll();
        return PackJson.packX(200,"添加成功",all);
    }

    @GetMapping("/del")
    public XJson del(Integer id){
        carouselService.del(id);
        List<Carousel> all = carouselService.findAll();
        return PackJson.packX(200,"删除成功",all);
    }
}
